// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <cantor/utility/json_reader.h>
#include <fstream>
#include <string>

namespace cantor {

    turbo::Result<nlohmann::ordered_json> read_file(const std::string& path) {
        std::string content;
        try {
            std::ifstream file(path, std::ios::binary);
            file.seekg(0, std::ios::end);
            size_t size = file.tellg();
            file.seekg(0);
            content.resize(size, '\0');
            file.read(content.data(), size);
        } catch (...) {
            return  turbo::invalid_argument_error("Failed to read file " , path);
        }

        try {
            auto json = nlohmann::ordered_json::parse(content);
            return json;
        } catch (...) {
            return  turbo::invalid_argument_error("Failed to parse file " , path);
        }
    }
}  // namespace cantor